#include "Gpio.h"

Gpio::Gpio(string num){
    this->m_num = num;

    this->fd = open(SYSFS_GPIO_EXPORT, O_WRONLY);

    if(this->fd == -1){
        printf("ERR: Radio hard reset pin open error.\n");
        return;
    }
    
    write(this->fd, this->m_num.c_str() ,this->m_num.size()); 
    cout<<"open "<< this->m_num << endl;
    close(this->fd); 

    //设置端口方向/sys/class/gpio/gpio137# echo out > direction

    string fileName = "/sys/class/gpio/gpio" + this->m_num +"/direction";
    this->fd = open(fileName.c_str(), O_WRONLY);

    if(this->fd == -1){
        printf("ERR: Radio hard reset pin direction open error.\n");
        return;
    }

    printf("echo out direction\r\n");

    write(this->fd, "out", sizeof("out")); 
    close(this->fd); 
                                                            
    //输出复位信号: 拉高>100ns
    fileName = "/sys/class/gpio/gpio"+this->m_num+"/value";
    this->fd = open(fileName.c_str(), O_RDWR);

    this->statue = 0;
}

Gpio::~Gpio(){
    // this->gpioClose();
    close(this->fd);
    // close(this->in_fd);
}

int Gpio::gpioOpen(){
    if(this->fd == -1){
        printf("ERR: Radio hard reset pin value open error.\n");
        return EXIT_FAILURE;
    }

    write(this->fd, SYSFS_GPIO_RST_VAL_H, sizeof(SYSFS_GPIO_RST_VAL_H));	
    cout<<"echo 1 > gpio"<<this->m_num<<endl;

    this->statue = 1;

    return EXIT_SUCCESS;
}

int Gpio::gpioClose(){
    if(this->fd == -1){
        printf("ERR: Radio hard reset pin value open error.\n");
        return EXIT_FAILURE;
    }
    
    write(this->fd, SYSFS_GPIO_RST_VAL_L, sizeof(SYSFS_GPIO_RST_VAL_L));	
    cout<<"echo 0 > gpio"<<this->m_num<<endl;

    this->statue = 0;

    return EXIT_SUCCESS;
}

int Gpio::getStatus(){

    return this->statue;
}